package com.lonwin.inspectionmanagement.app.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jess.arms.base.BaseService;
import com.lh.features.LhCoordinate;
import com.lh.util.LhCoordUtil;
import com.lonwin.inspectionmanagement.R;
import com.lonwin.inspectionmanagement.mvp.ui.activity.HomeActivity;

import org.simple.eventbus.EventBus;

import butterknife.internal.Utils;

public class LocationService extends BaseService implements  AMapLocationListener{
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    boolean isCreateChannel = false;
    private boolean isloop = false;//启动服务的时候是否循环定位，默认true
    private Intent myIntent = null;

    public LocationService() {
    }



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        myIntent = intent;
        return super.onBind(intent);

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.hasExtra("isloop")) {
            isloop = intent.getBooleanExtra("isloop", true);
        }
        if (mLocationClient != null) {
            mLocationClient.startLocation();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void init() {

        if (myIntent != null && myIntent.hasExtra("isloop")) {
            isloop = myIntent.getBooleanExtra("isloop", true);
        }
        mLocationClient = new AMapLocationClient(this);

        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //注册监听函数
//        notificationFor8();
        initLocation();

}
    /**
     * 针对安卓8.0新特性阻止后台持续定位，使用前台服务
     */
//    public void notificationFor8() {
//        //开启前台定位服务：
//        Notification.Builder builder = new Notification.Builder(getApplicationContext());
//        //获取一个Notification构造器
//        Intent nfIntent = new Intent(LocationService.this.getApplicationContext(), HomeActivity.class);
//        builder.setContentIntent(PendingIntent.getActivity(LocationService.this, 0, nfIntent, 0)) // 设置PendingIntent
//                .setContentTitle("正在进行后台定位") // 设置下拉列表里的标题
////                .setSmallIcon(R.drawable.ic_launcher) // 设置状态栏内的小图标
//                .setContentText("后台定位通知") // 设置上下文内容
//                .setAutoCancel(true)
//                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
//
//        notification = builder.build();
//        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
//        startForeground(1,notification);
//    }
    public void initLocation(){
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        Notification notification=buildNotification();
        mLocationClient.enableBackgroundLocation(2001, notification);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(1000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);

//停止前台定位服务：
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(100,notification);
        }

    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        LhCoordinate lhCoordinate=LhCoordUtil.gcj_To_Wgs84(LhCoordinate.fromDegrees(aMapLocation.getLatitude(),aMapLocation.getLongitude()));
        aMapLocation.setLatitude(lhCoordinate.getLatitude());
        aMapLocation.setLongitude(lhCoordinate.getLongitude());
        if (aMapLocation.getLatitude()>10&&aMapLocation.getLongitude()>10)
        {
            EventBus.getDefault().post(aMapLocation);
            if (!isloop) {
                mLocationClient.stopLocation();
            }
        }
    }


    @SuppressLint("NewApi")
    private Notification buildNotification() {
        Notification notification=null;
        Notification.Builder builder = null;
        String channelId = getPackageName();
        if(android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            }

            if(!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.drawable.record_icon)
                .setContentTitle("巡查管理")
                .setContentText("正在后台运行")
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.disableBackgroundLocation(true);
        mLocationClient.onDestroy();
    }
}
